import { _decorator, Component, Sprite, Color, tween } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('RedBlinkEffect')
export class RedBlinkEffect extends Component {
    @property(Sprite)
    targetSprite: Sprite | null = null; // 目标精灵组件
    @property
    blinkDuration: number = 0.02; // 单次闪烁持续时间
    @property
    blinkCount: number = 1; // 闪烁次数
    @property
    intensity: number = 1.0; // 红色强度 (0-1)
    @property
    nextInterval: number = 0.2; // 下一次可再次闪烁的时间间隔
    
    private originalColor: Color | null = null; // 原始颜色

    private isBlinkEffect:boolean = false;
    
    onLoad() {
        this.blinkDuration = 0.08;
        // 自动获取精灵组件
        if (!this.targetSprite) {
            this.targetSprite = this.getComponent(Sprite);
        }
        // 保存原始颜色
        if (this.targetSprite) {
            this.originalColor = this.targetSprite.color.clone();
        }
        // this.schedule(function(){
        //     this.startBlink();
        // }.bind(this), 3);
    }

    onEnable()
    {
        this.isBlinkEffect = true;
    }
    
    // 开始闪烁
    startBlink() {
        if (!this.targetSprite || !this.originalColor || !this.isBlinkEffect) return;
        
        this.isBlinkEffect = false;
        this.scheduleOnce(function(){
            this.isBlinkEffect = true;
        }.bind(this), this.nextInterval);
        // 停止可能正在进行的闪烁
        this.stopBlink();
        // 创建红色
        const redColor = new Color(
            this.originalColor.r * this.intensity,
            this.originalColor.g * (1 - this.intensity),
            this.originalColor.b * (1 - this.intensity),
            this.originalColor.a
        );
        
        // 闪烁动画
        for (let i = 0; i < this.blinkCount; i++) {
            const delay = i * this.blinkDuration * 2;
            tween(this.targetSprite)
                .delay(delay)
                .to(this.blinkDuration, { color: redColor })
                .to(this.blinkDuration, { color: this.originalColor })
                .start();
        }
    }
    
    // 停止闪烁
    stopBlink() {
        if (!this.targetSprite || !this.originalColor) return;
        
        tween(this.targetSprite).stop();
        this.targetSprite.color = this.originalColor.clone();
    }
    
    // 简单调用示例
    blinkOnce() {
        this.blinkCount = 1;
        this.startBlink();
    }
}